<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.userName" class="list-input" placeholder="搜索用户名称" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.userName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">登录地址</text>
            <uni-easyinput v-model="queryParams.ipaddr" placeholder="请输入登录地址" :clearable="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">登录状态</text>
            <BottomSelect v-model="queryParams.status" :options="statusOptions" value-field="value" label-field="text"
                          placeholder="请选择状态" title="选择状态"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-danger" @click="handleClean">
        <uni-icons type="trash" size="14" color="#ff3b30"/>
        <text>清空</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 列表 -->
    <view class="list-content">
      <view v-for="log in loginInfoList" :key="log.infoId" class="list-item" @click="handleView(log)">
        <view class="list-avatar">
          <uni-icons type="person-filled" size="24" :color="log.status === '0' ? '#52c41a' : '#ff4d4f'"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ log.userName }}</text>
            <text class="list-subtitle">{{ log.loginLocation || '未知位置' }}</text>
            <view class="status-badge" :class="log.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ log.status === '0' ? '成功' : '失败' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">ID：{{ log.infoId }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="location" size="14" color="#999"/>
              <text class="detail-text">{{ log.ipaddr }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(log.loginTime, '{y}-{m}-{d} {h}:{i}') }}</text>
            </view>
            <view class="detail-item" v-if="log.browser">
              <uni-icons type="search" size="14" color="#999"/>
              <text class="detail-text">{{ log.browser }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleView(log)">
            <uni-icons type="eye" size="14" color="#007aff"/>
            <text class="action-text">详情</text>
          </view>
          <view class="action-btn action-danger" v-if="log.status === '1'" @click.stop="handleDelete(log)">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="loginInfoList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText" @clickLoadMore="handleLoadMore"/>
    </view>

    <view v-if="!loading && loginInfoList.length === 0" class="list-empty">
      <uni-icons type="info" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无登录日志</text>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {cleanLoginInfo, delLoginInfo, list} from '@/api/monitor/loginInfo'
import {parseTime} from '@/utils/ruoyi'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()

// 数据定义
const loginInfoList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')
const filterPopup = ref(null)
let searchTimer = null

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  ipaddr: '',
  status: ''
})

// 状态选项
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '成功'},
  {value: '1', text: '失败'}
]

// 页面加载
onMounted(() => {
  getList()
})

// 获取登录日志列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await list(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        loginInfoList.value = newData
      } else {
        loginInfoList.value.push(...newData)
      }

      total.value = response.total || 0

      if (loginInfoList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取登录日志列表失败:', error)
    proxy.$modal.showToast('获取登录日志列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 筛选相关函数
function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {pageNum: 1, pageSize: 10, userName: '', ipaddr: '', status: ''})
}

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.userName = '';
  handleQuery()
}

function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  loginInfoList.value = []
  getList()
}

// 业务操作方法
function handleView(log) {
  uni.navigateTo({
    url: `./detail?infoId=${log.infoId}`
  })
}

async function handleDelete(log) {
  try {
    await proxy.$modal.confirm(`确认要删除登录日志"${log.infoId}"吗？`)

    const response = await delLoginInfo(log.infoId)
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      handleQuery()
    }
  } catch (error) {
    console.error('删除登录日志失败:', error)
  }
}


async function handleClean() {
  try {
    await proxy.$modal.confirm('确认要清空所有登录日志吗？')

    const response = await cleanLoginInfo()
    if (response.code === 200) {
      proxy.$modal.showToast('清空成功')
      handleQuery()
    }
  } catch (error) {
    console.error('清空登录日志失败:', error)
  }
}

function handleRefresh() {
  handleQuery()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';
</style>